<template>
  <el-card class="box-card" >
    <div slot="header" class="clearfix">
      <el-select v-model="currBuilding"  placeholder="楼宇">
        <el-option v-for="build in buildingList" :key="build.number" :label="build.name" :value="build.number"></el-option>
      </el-select>


      <el-button style="float: right; padding: 3px 0" size="medium" type="text" @click="zft = true" v-if="buildInfo">总房态</el-button>
      <div style="float: right;padding: 2px 200px;width: 20%;" >
        <div style="float: right;margin-left:10px; "> <span style="margin-bottom: 1px;width: 5px;height:5px;background: #1cb8eb;display: inline-block; "></span><span style="margin-left: 5px;font-size: 14px;">预定中</span></div>

        <div style="float: right;"> <span style="width: 5px;margin-bottom: 1px;height:5px;background: #e6a23c;display: inline-block; "></span><span style="margin-left: 5px;font-size: 14px;">使用中</span></div>
        <div style="float: right;margin-right:10px; "> <span style="width: 5px;height:5px;background: #66ccaa;display: inline-block; "></span><span style="margin-left: 5px;font-size: 14px;">空闲</span></div>

      </div>
    </div>
    <div v-if="buildInfo">
      <div v-for="(roominfos, key) in buildInfo.floorRoomInfos" :key="key" class="text item" id="menu">
        <span style="font-size: 30px; color: #ffcc66">{{key}}</span>

          <el-row>
            <el-col :span="5" v-for="(room, index) in roominfos" :key="index" :offset="index % 4 != 0 ? 1 : 0">
              <el-card :body-style="{ padding: '0px' }" style="background-color: #c7efcf">
                <div style="padding: 7px;">
                  <div class="bottom clearfix" style="height: 161px;">
                    <table class="ctltable" style="font-size: 1px; background-color: #66ccaa;width: 100%;height: 100%;" >

                      <tr >
                        <td :colspan="room.bedInfos?room.bedInfos.length:1" style="background-color: #ffcc66">
                          {{ room.roomInfo.roomCode }}号房（{{room.roomInfo.roomTypeName}}） （{{room.roomInfo.roomOrientationName}}）
                        </td>
                      </tr>
                      <tr >


                        <td  v-for="(bed, bindex) in room.bedInfos" :key="bindex" style="background-color: #66ccaa;width: 10%; border-top-style:none;border-bottom-style:none" :class="{'redRoom': bed.bedInfo.status == 0, 'greenRoom1': (bed.bedInfo.status) == 1, 'greenRoom2':bed.bedInfo.status==2 }"   >
                          <span style="float: left;margin-top: -6px;padding-left: 2px; font-family: '微软雅黑'"  :style="{'margin-top':bed.bedInfo.status!=2? '5px':'-6px'}"> {{ bed.bedInfo.bedCode }}床</span>
<!--                          <span style=" float:right;margin-right:5px;border-radius:5px;width: 5px;height:5px;background: #66ccaa;display: inline-block;" v-if="bed.bedInfo.status==0"></span>-->
<!--                          <span style="float:right;margin-right:5px;border-radius:5px;width: 5px;height:5px;background: #e6a23c;display: inline-block;" v-if="bed.bedInfo.status==2"></span>-->
<!--                          <span style="float:right;margin-right:5px;border-radius:5px;width: 5px;height:5px;background: #f56c6c;display: inline-block;" v-if="bed.bedInfo.status==1"></span>-->

                          <div  style="height: 100%" v-if="bed.bedInfo.status!=2&&bed.bedInfo.status!=1" @contextmenu.prevent="openMenu($event,(bed))">

                          </div>

                          <div   style="height: 100%" v-if="bed.bedInfo.status==1" >

                          </div>
                        </td>

                      </tr>
                      <tr  >

                        <td    v-for="(bed, bindex) in room.bedInfos" :key="bindex" style="background-color: #66ccaa; border-top-style:none;border-bottom-style:none" :class="{'redRoom': bed.bedInfo.status == 0, 'greenRoom1': (bed.bedInfo.status) == 1, 'greenRoom2':bed.bedInfo.status==2 }" 	>

                          <div  style="height: 100%" v-if="bed.bedInfo.status!=2&&bed.bedInfo.status!=1" @contextmenu.prevent="openMenu($event,(bed))">

                          </div>
                          <!--<el-button v-if="bed.bedInfo.status == 0 && !room.compartment" type="text" size="mini">预定</el-button>-->
                          <p  v-if="bed.bedInfo.status == 2" style="padding:0px 5px;white-space:nowrap;line-height: 20px;">
                            {{bed.checkInName}}
                          </p>
                          <p v-if="bed.bedInfo.status == 2" style="padding:0px 5px;white-space:nowrap;line-height: 20px;">
                            {{bed.age}}<span style=" white-space:nowrap;line-height: 20px;"></span>
                          </p>
                          <p v-if="bed.bedInfo.status == 2" style="padding:0px 5px;line-height: 20px;" >
                            {{bed.genderName}}
                          </p>
                          <p  v-if="bed.bedInfo.status == 2" style="padding:0px 5px;line-height: 20px;">
                            <span>{{bed.nursingLevelName}}</span>
                          </p>
                          <p>
                          <el-tag v-if="room.compartment" type="success" size="mini">包房</el-tag>
                        </p>


                        </td>
                      </tr>
                    </table>

                  </div>
                </div>
              </el-card>
            </el-col>

        </el-row>

    </div>
    <div>
    </div>

    </div>
    <el-drawer
      title="总房态"
      :visible.sync="zft"
      direction="rtl"
      size="20%">
      <table style="width: 100%" v-if="buildInfo" >
        <tr style="background-color: #44aaee">
          <td style="color: #ffcc66; font-size: 15px; font-weight: bold">总床位:&nbsp; {{buildInfo.totalNumber}}</td>
        </tr>
        <tr style="background-color: #2cc642">
          <td style="color: #ffcc66; font-size: 15px; font-weight: bold">空&nbsp; &nbsp; &nbsp; &nbsp; 闲:&nbsp; {{buildInfo.freeNumber}}</td>
        </tr>
        <tr style="background-color: #66ccaa">
          <td style="color: #ffcc66; font-size: 15px; font-weight: bold">入&nbsp; &nbsp; &nbsp; &nbsp; 住:&nbsp; {{buildInfo.checkInNumber}}</td>
        </tr>
        <tr style="background-color: #666666">
          <td style="color: #ffcc66; font-size: 15px; font-weight: bold">预&nbsp; &nbsp; &nbsp; &nbsp; 定:&nbsp; {{buildInfo.bookNumber}}</td>
        </tr>
      </table>
    </el-drawer>
    <ul v-show="visible" :style="{left:left+'px',top:top - 150 + 'px'}" class="contextmenu">
      <li @click="proceed">
           预定床位
      </li>

    </ul>
    <el-dialog
      :title="'填写预定信息'+'（'+title+'）'"
      :visible.sync="dialogFormVisible"
      destroy-on-close

    >
      <el-container>

        <el-main>
          <el-form ref="form"     :model="form"  :rules="rules"  >
            <el-row>

              <el-col :span="10">
                <el-form-item label="老人姓名" prop="elderlyName">
                  <el-input v-model="form.elderlyName"  style="width: 100%" ></el-input>
                </el-form-item>
              </el-col>

                <el-col :span="10" style="margin-left: 20px">
                  <el-form-item label="老人身份证" prop="elderlyCardNo">
                    <el-input  v-model="form.elderlyCardNo"  onkeyup="this.value=this.value.replace(/[^\X0-9]/g, '')" style="width: 100%" ></el-input>
                  </el-form-item>
                </el-col>



            </el-row>
            <el-row>
              <el-col :span="10" >

                <el-form-item label="预定人姓名" prop="bookerName" >
                  <el-input v-model="form.bookerName"    style="width: 100%;" @blur="phone" ></el-input>

                </el-form-item>
              </el-col>

              <el-col :span="10" style="margin-left: 20px">
                <el-form-item label="预定人联系电话" prop="contactNumber"   >
                  <el-input  v-model="form.contactNumber"  style="width: 100%" @blur="phone"></el-input>
                </el-form-item>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10" >
                <el-form-item label="老人出生日期" prop="elderlyBirth">

                  <el-date-picker
                    v-model=" form.elderlyBirth"
                    type="date"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    placeholder="出生日期">
                  </el-date-picker>

                </el-form-item>
              </el-col>
              <el-col :span="10" >
              <el-form-item label="性别"style="margin-left: 20px" required>
                <el-select v-model="radio" style="width: 110%" placeholder="请选择">
                  <el-option

                    v-for="item in radios"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              </el-col>
            </el-row>


            <el-row>
              <el-col :span="10">
                <el-form-item label="预定人与老人关系" required>
                  <el-select v-model="relationship" style="width: 100%" placeholder="请选择">
                    <el-option
                      v-for="item in relationships"
                      :key="item.dcNo"
                      :label="item.name"
                      :value="item.dcNo">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="10" style="margin-left: 20px">
                <el-form-item label="计划入住时间" prop="plannedCheckInTime" >
                  <el-date-picker
                    v-model="form.plannedCheckInTime"
                    type="date"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    placeholder="计划入住时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>


            <el-form-item label="备注信息" >
              <el-input  type="textarea" v-model="form.remark"  ></el-input>
            </el-form-item>


          </el-form>
        </el-main>




        <el-aside >

          <el-header style="text-align: center; font-size: 14px;height: 30px">

            <span>咨询记录</span>
          </el-header>
          <el-table
            v-if="!isdisabled"
            class="active"
            ref="singleTable"
            :data="tableData"
            highlight-current-row
            @row-click="handleRowClick"
            @current-change="handleCurrent"
            style="width: 100%;cursor:pointer">
            <el-table-column
              property="consultantName"
              label="咨询人姓名"
              width="120"
            >
            </el-table-column>

            <el-table-column
              property="elderlyName"
              label="老人姓名"
              width="120px"
            >
            </el-table-column>

            <el-table-column

              property="consultantRelationshipName"
              label="咨询人与老人关系"
              width="200">
            </el-table-column>
            <el-table-column

              property="consultantContactNumber"
              label="联系方式"
              width="200">
            </el-table-column>
            <el-table-column
              property="elderlyGenderName"
              label="性别"
            >
            </el-table-column>
            <el-table-column
              property="elderlySelfCareName"
              label="自理情况"
            >
            </el-table-column>
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button >取 消</el-button>
            <el-button type="primary" >确 定</el-button>
          </div>




        </el-aside>

      </el-container>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary"  @click="save">确 定</el-button>
      </div>

    </el-dialog>
  </el-card>
</template>

<script>
  import {searchBuildingOfOrgan, searchBuildingStatus} from "@/api/bed"
  import Template from "../../nursing/template";
  import { isIdentityId } from "@/api/validate"
  import { searchrecordCode,add } from "@/api/reserve"
    export default {
        name: "",
        components: {Template},
        data(){
            var checkIdentitytionId  = (rule, value, callback) => {
                var errorMsg = isIdentityId(value);
                if (errorMsg != "") {
                    callback(new Error(errorMsg));
                }else {

                    this.getBirthdayFromIdCard(value)
                    this.getradio(value)
                    callback();
                }

            }
          return {
            buildingList: [],
              isdisabled:false,
              relationships:{

              },
              scrollerWidth:'40%',
              relationship:"",
              tableData:[],
              dictionary:{

              },
              title:"",
              form:{
                  receptionCode:"",//接待编号
                  bookerName:"",//预定人姓名
                  elderlyName:"",//老人姓名
                  contactNumber:"",//预定人联系电话
                  elderlyCardNo:"",//老人身份证号
                  elderlyGender:"",//老人性别
                  elderlyBirth:"",//老人出生日期
                  institutionNumber:"",//所属机构编号
                  plannedCheckInTime:"",//计划入住时间
                  relationship:"",//预定人与老人关系
                  remark:"",//备注
                  buildingNumber:"",//楼宇编号
                  unit:"",//楼宇单元
                  floor:"",//楼宇楼层
                  roomNumber:"",//房间编号
                  bedNumber:""//床位编号
              },
              radio:1,
              radios: [{
                  value: 1,
                  label: '男'
              }, {
                  value: 0,
                  label: '女'
              }],
              rules: {

                  elderlyCardNo: [
                      {required: true, validator: checkIdentitytionId , trigger: "blur" }
                  ],
                  bookerName:[
                      {required: true, message: '预定人姓名', trigger: "blur" }
                  ],
                  elderlyName:[
                      {required: true, message: '老人姓名', trigger: "blur" }
                  ],
                  contactNumber:[
                      {required: true, message: '预定人联系电话', trigger: "blur" }
                  ],
                  elderlyBirth:[
                      {required: true, message: '出生日期', trigger: "change" }
                  ],
                  plannedCheckInTime:[
                      {required: true, message: '计划入住时间', trigger: "change" }
                  ],
              },
              flage:1,
            currBuilding: undefined,
            buildInfo: undefined,
            zft: false,
              top: 0,
              left: 0,
              visible:false,
              selectedTag: {},
              dialogFormVisible:false
          }

        },
      methods: {
          openMenu(e,row) {
              const menuMinWidth = 105
              const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
              const offsetWidth = this.$el.offsetWidth // container width
              const maxLeft = offsetWidth - menuMinWidth // left boundary
              const left = e.clientX - offsetLeft + 15 // 15: margin right

              if (left > maxLeft) {
                  this.left = maxLeft
              } else {
                  this.left = left
              }
              console.log(this)
              this.top = e.pageY
              // this.top = e.clientY
              this.visible = true








              this.title=(row.bedInfo.unit+'单元'+row.bedInfo.floor+'楼'+row.bedInfo.roomCode+'房'+row.bedInfo.bedCode+'床')
              this.form.institutionNumber=row.bedInfo.institutionNumber
              this.form.buildingNumber=row.bedInfo.number
              this.form.unit=row.bedInfo.unit
              this.form.floor=row.bedInfo.floor
              this.form.roomNumber=row.bedInfo.roomCode
              this.form.bedNumber=row.bedInfo.bedCode



          },
          closeMenu() {
              this.visible = false

          },
          proceed(){
              this.isdisabled = false
              this.tableData=[]
              this.scrollerWidth=40+'%'
              this.buildingNumber=""
              this.radio=1
              this.relationship=1
              this.form.bookerName=""
              this.form.elderlyName=""
              this.form.contactNumber=""
              this.form.elderlyCardNo=""
              this.form.plannedCheckInTime=""
              this.form.elderlyBirth=""
              this.form.remark=""


          this.$nextTick(() => {
              this.$refs['form'].clearValidate();
          })
              this.dialogFormVisible=true

          },
          getBirthdayFromIdCard(idCard) {
              var birthday = "";
              if(idCard != null && idCard != ""){
                  if(idCard.length == 15){
                      birthday = "19"+idCard.substr(6,6);
                  } else if(idCard.length == 18){
                      birthday = idCard.substr(6,8);
                  }

                  birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
              }

              this.form.elderlyBirth=birthday
          },
          getradio(idCard){
              if (parseInt(idCard.substr(16, 1)) % 2 == 1) {
                  this.radio=1

              } else {
                  this.radio=0

              }
          },
          handleCurrent(val) {

              this.flage=1
              this.currentRow = val;
              if(this.currentRow){
                  this.relationship=this.currentRow.consultantRelationship
                  this.form.receptionCode=this.currentRow.code
                  this.form.elderlyName=this.currentRow.elderlyName
                  this.form.bookerName=this.currentRow.consultantName
                  this.form.contactNumber=this.currentRow.consultantContactNumber
              }

          },
          handleRowClick(){
              this.flage++
              console.log(this.flage)
              if(this.flage===3){

                  this.setCurrent()
                  this.flage=1
              }
          },
          setCurrent(row) {
              this.relationship=1
              this.form.receptionCode=""
              this.form.elderlyName=""
              this.form.bookerName=""
              this.form.contactNumber=""
              this.$refs.singleTable.setCurrentRow(row);
              console.log(this.form)

          },
          phone(){

              if(this.form.contactNumber!=="" && (/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.form.contactNumber))){
                  let consultant=this.form.contactNumber
                  searchrecordCode({consultant}).then(res =>{
                      console.log(res.data)
                      this.tableData=res.data


                  })

                  this.diaphone=true
              }else {
                  if(this.form.bookerName){
                      let consultant=this.form.bookerName
                      searchrecordCode({consultant}).then(res =>{
                          console.log(res.data)
                          this.tableData=res.data


                      })
                  }

              }



          },
          saveadd(){
              console.log(this.currentRow)
              if(this.currentRow){
                  this.relationship=this.currentRow.consultantRelationship
                  this.form.receptionCode=this.currentRow.code
                  this.form.elderlyName=this.currentRow.elderlyName
                  this.form.bookerName=this.currentRow.consultantName
                  this.form.contactNumber=this.currentRow.consultantContactNumber
              }

              this.diaphone=false
          },
          save(){

              this.$refs['form'].validate(async (valid) => {

                  this.form.elderlyGender=this.radio
                  this.form.relationship=this.relationship
                  if (valid) {

                          console.log(this.form)
                          const {code,data} = await add(this.form);
                          console.log(data)
                          if(code==200){
                              this.$message({
                                  message: "预定成功",
                                  type: 'success'
                              })

                              this.searchRooms()
                              this.dialogFormVisible=false

                          }else {

                          }








                  }
                  else {
                      return false;
                  }
              });

              console.log(this.form)
          },
          async searchBuildings(){
            let result = await searchBuildingOfOrgan()
            if(result.code == '200'){
              this.buildingList = result.data
              if(this.buildingList && this.buildingList.length > 0){
                this.currBuilding = this.buildingList[0].number
              }
            }else{
              this.$baseMessage('查询楼宇信息失败，'+result.message)
            }
          },
          async searchRooms(){
            if(this.currBuilding){
              let result = await searchBuildingStatus(this.currBuilding)
              if(result.code == '200'){
                this.buildInfo = result.data
              }else{
                this.buildInfo = undefined
              }
            }
          }
      },
      watch: {
        currBuilding(val, oldVal){//普通的watch监听
          this.searchRooms()
        },
          visible(value) {
              if (value) {
                  document.body.addEventListener('click', this.closeMenu)
              } else {
                  document.body.removeEventListener('click', this.closeMenu)
              }
          }
      },
      mounted(){
          this.dictionary=JSON.parse(localStorage.getItem("dictionary"))
          for(var i=0;i<this.dictionary.length;i++) {
              if (this.dictionary[i].mark == "relationship") {
                  this.relationships = (this.dictionary[i].childs)
              }
          }
          this.form.institutionNumber=localStorage.getItem("institutionNumber")
          this.searchBuildings()
      }
    }
</script>
<style lang="scss" scoped>

    .contextmenu {
      margin: 0;
      background: #fff;
      z-index: 3000;
      position: absolute;
      list-style-type: none;
      padding: 5px 0;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 400;
      color: #333;
      box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);
      li {
        margin: 0;
        padding: 7px 10px;
        cursor: pointer;
        &:hover {
          background: #eee;
        }
      }
    }

</style>
<style scoped>
  .text {
    font-size: 20px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    width: 100%;
  }


  table
  {
    border-collapse: collapse;
    margin: 0 auto;
    text-align: center;
  }
  table td, table th
  {
    border: 1px solid #cad9ea;
    height: 30px;
  }
  table .ttitle
  {
    background-color: #F5FAFA;
    width: 100px;
  }
  table tr:nth-child(odd)
  {
    background: #fff;
  }
  .redRoom{
    background: #66ccaa !important;
    height: 100%;
  }

  .greenRoom1{
    background: #1cb8eb !important;
    height: 100%;
  }

  .greenRoom2{
    background: #e6a23c !important;
  }
  .el-col-5 {
    width: 21.833333%;
  }
  .ctltable{
    border-collapse: collapse;
    table-layout:fixed}
  .ctltable td {
    text-overflow:ellipsis;
    overflow:hidden;
    white-space: nowrap;
    padding:2px}
  .active >>> .el-table__body tr.current-row > td{
    background-color: #409eff !important
  }
  .active >>> .el-table__body tr.current-row > td .cell{
    color: #ffffff !important
  }
  .active >>>.el-table__body tr:hover>td {
    background-color: #409eff !important;
    color: #ffffff;
  }
</style>
<style>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 30px;
  }

  .el-aside {
    color: #333;
  }
</style>
